package side_server;

import java.io.IOException;
import java.net.UnknownHostException;

import talk_server.Talker;

public class Ping implements Runnable{
	private boolean 	running=true;
	private String		peerList;				
	
	public Ping()
	{
		super();
	}
	
	@Override
	public synchronized void run() {
		
		while (running)
		{
			try {
				Thread.sleep(30000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			peerList = Server_Launch.getInstance().getPeerList();
			String[] peers=peerList.split(Server_Launch.SEP);
			for(int i=0;i<peers.length-1;i++)
			{	//Provo tutti i server nell'elenco per vedere quali sono
				//ancora attivi
				System.out.println("CHECKING PEER " + peers[i]);
				String	aPeer = peers[i];
				String[] addr = aPeer.split(" ");
				String ip   = addr[0];
				int    port = Integer.parseInt(addr[1]); 
				Talker talker = null;
				try {
					talker = new Talker(ip,port);
					talker.write("HELLO");
					talker.read();
					System.out.println(aPeer + " IS ALIVE");
					talker.close();
				} catch (UnknownHostException e1) {
					System.out.println("REMOVE PEER " + aPeer);
					Server_Launch.getInstance().removePeer(aPeer);
				} catch (IOException e1) {
					System.out.println("REMOVE PEER " + aPeer);
					Server_Launch.getInstance().removePeer(aPeer);
				}
			}
		}		
	}
	
	public void Stop()
	{
		running=false;
	}
}
